package com.wl.jxy.excel;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelUtil {
    public static void main(String[] args) throws Exception{
        List<Student> list=new ArrayList<>();
        //for (int i = 0; i < 100; i++) {
            list.add(new Student("java",6,"男", new Date()));
            list.add(new Student("php",7,"男", new Date()));
            list.add(new Student("c",8,"nv", new Date()));
        //}
        //创建2003 excel
        //creat2003Excel(list);

        //创建2007 excel
        //creat2007Excel(list);

        /**
         * 调用共用读取方法时，一次只能读取一个文件
         */
        //读取2003 ecxel
      /*  List<Student> students03= readExcel(new File("E:/excel_2003.xls"));
        System.out.println("2003Excel内容：");
        for (Student s:
            students03) {
            System.out.println(s);
        }
        System.out.println("2003Excel读取结束");*/

        //读取2007 ecxel
        List<Student> students07=readExcel(new File("E:/excel_2007.xlsx"));
        System.out.println("2007Excel内容：");
        for (Student s:
            students07) {
            System.out.println(s);
        }
        System.out.println("2007Excel读取结束");
    }

    /**
     * 创建2003版本的Excel文件
     */
    private static void creat2003Excel(List<Student> list) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();// 创建 一个excel文档对象

        HSSFSheet sheet = workbook.createSheet();// 创建一个工作薄对象

        // 添加表头行
        HSSFRow hssfRow = sheet.createRow(0);
        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        sheet.setColumnWidth(3, 6000);//设置第四列列宽

        // 添加表头内容
        HSSFCell headCell = hssfRow.createCell(0);
        headCell.setCellValue("姓名");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(1);
        headCell.setCellValue("年龄");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(2);
        headCell.setCellValue("性别");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(3);
        headCell.setCellValue("时间");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < list.size(); i++) {
            hssfRow = sheet.createRow((int) i + 1);
            Student student = list.get(i);

            // 创建单元格，并设置值
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(student.getName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(1);
            cell.setCellValue(student.getAge());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(2);
            cell.setCellValue(student.getSex());
            cell.setCellStyle(cellStyle);

            HSSFCellStyle dateStyle = workbook.createCellStyle();
            dateStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格格式居中
            dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));//设置时间格式
            cell = hssfRow.createCell(3);
            cell.setCellValue(student.getDate());
            cell.setCellStyle(dateStyle);
        }

        // 保存Excel文件
        try {
            OutputStream outputStream = new FileOutputStream("E:/excel_2003.xls");
            workbook.write(outputStream);
            outputStream.close();
            System.out.println("创建成功 office 2003 excel");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建2007版Excel文件
     *
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void creat2007Excel(List<Student> list) throws Exception {
        // HSSFWorkbook workbook = new HSSFWorkbook();// 创建 一个excel文档对象
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();// 创建一个工作薄对象

        // 添加表头行
        XSSFRow xssfRow = sheet.createRow(0);
        // 设置单元格格式居中
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        sheet.setColumnWidth(3, 6000);//设置第四列列宽
        // 添加表头内容
        XSSFCell headCell = xssfRow.createCell(0);
        headCell.setCellValue("姓名");
        headCell.setCellStyle(cellStyle);

        headCell = xssfRow.createCell(1);
        headCell.setCellValue("年龄");
        headCell.setCellStyle(cellStyle);

        headCell = xssfRow.createCell(2);
        headCell.setCellValue("性别");
        headCell.setCellStyle(cellStyle);

        headCell = xssfRow.createCell(3);
        headCell.setCellValue("时间");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < list.size(); i++) {
            xssfRow = sheet.createRow((int) i + 1);
            Student student = list.get(i);

            // 创建单元格，并设置值
            XSSFCell cell = xssfRow.createCell(0);
            cell.setCellValue(student.getName());
            cell.setCellStyle(cellStyle);

            cell = xssfRow.createCell(1);
            cell.setCellValue(student.getAge());
            cell.setCellStyle(cellStyle);

            cell = xssfRow.createCell(2);
            cell.setCellValue(student.getSex());
            cell.setCellStyle(cellStyle);

            XSSFCellStyle dateStyle = workbook.createCellStyle();
            dateStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 设置单元格格式居中
            dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));//设置时间格式
            cell = xssfRow.createCell(3);
            cell.setCellValue(student.getDate());
            cell.setCellStyle(dateStyle);
        }

        // 保存Excel文件
        try {
            OutputStream outputStream = new FileOutputStream("E:/excel_2007.xlsx");
            workbook.write(outputStream);
            outputStream.close();
            System.out.println("创建成功 office 2007 excel");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 对外提供读取excel 的方法（根据文件名后缀名判断是2003还是2007excel文件）
     */
    public static List<Student> readExcel(File file) throws IOException {
        String fileName = file.getName();
        String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName
                .substring(fileName.lastIndexOf(".") + 1);
        if ("xls".equals(extension)) {
            return read2003Excel(file);
        } else if ("xlsx".equals(extension)) {
            return read2007Excel(file);
        } else {
            throw new IOException("不支持的文件类型");
        }
    }

    /**
     * 读取 office 2003 excel
     *
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static List<Student> read2003Excel(File file)
            throws IOException {
        List<Student> list = new ArrayList<>();
        HSSFWorkbook workbook = null;

        try {
            // 读取Excel文件
            InputStream inputStream = new FileInputStream(file);
            workbook = new HSSFWorkbook(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 循环工作表
        if (workbook != null) {
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                HSSFSheet hssfSheet = workbook.getSheetAt(numSheet);
                if (hssfSheet == null) {
                    continue;
                }
                // 循环行
                for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }

                    // 将单元格中的内容存入集合
                    Student student = new Student();

                    HSSFCell cell = hssfRow.getCell(0);
                    if (cell == null) {
                        continue;
                    }
                    student.setName(cell.getStringCellValue());

                    cell = hssfRow.getCell(1);
                    if (cell == null) {
                        continue;
                    }
                    student.setAge((int) cell.getNumericCellValue());

                    cell = hssfRow.getCell(2);
                    if (cell == null) {
                        continue;
                    }
                    student.setSex(cell.getStringCellValue());

                    cell = hssfRow.getCell(3);
                    if (cell == null) {
                        continue;
                    }
                    student.setDate(cell.getDateCellValue());

                    list.add(student);
                }
            }
        }
        return list;
    }

    /**
     * 读取Office 2007 excel
     */

    private static List<Student> read2007Excel(File file)
            throws IOException {
        List<Student> list = new ArrayList<>();
        XSSFWorkbook workbook = null;

        try {
            // 读取Excel文件
            InputStream inputStream = new FileInputStream(file);
            workbook = new XSSFWorkbook(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 循环工作表
        if (workbook != null) {
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                XSSFSheet xssfSheet = workbook.getSheetAt(numSheet);
                if (xssfSheet == null) {
                    continue;
                }
                // 循环行
                for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow == null) {
                        continue;
                    }

                    // 将单元格中的内容存入集合
                    Student student = new Student();

                    XSSFCell cell = xssfRow.getCell(0);
                    if (cell == null) {
                        continue;
                    }
                    student.setName(cell.getStringCellValue());

                    cell = xssfRow.getCell(1);
                    if (cell == null) {
                        continue;
                    }
                    student.setAge((int) cell.getNumericCellValue());

                    cell = xssfRow.getCell(2);
                    if (cell == null) {
                        continue;
                    }
                    student.setSex(cell.getStringCellValue());

                    cell = xssfRow.getCell(3);
                    if (cell == null) {
                        continue;
                    }
                    student.setDate(cell.getDateCellValue());

                    list.add(student);
                }
            }
        }
        return list;
    }

}
